package cn.tedu._05weibo.controller;

import cn.tedu._05weibo.base.response.JsonResult;
import cn.tedu._05weibo.base.response.StatusCode;
import cn.tedu._05weibo.mapper.UserMapper;
import cn.tedu._05weibo.pojo.dto.UserLoginParam;
import cn.tedu._05weibo.pojo.dto.UserRegParam;
import cn.tedu._05weibo.pojo.entity.User;
import cn.tedu._05weibo.pojo.vo.UserVO;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;
import java.util.Date;

@Slf4j
@RestController
@Api(tags = "01.用户管理功能")
@RequestMapping("/v1/user")
public class UserController {
    @Autowired
    UserMapper userMapper;
    @PostMapping("reg")
    @ApiOperation("用户注册")
    @ApiOperationSupport(order=10)
    public JsonResult reg(@Validated @RequestBody UserRegParam userRegParam) {
        log.debug("userRegParam=" + userRegParam);
        String username = userRegParam.getUsername();
        int num = userMapper.selectByusername(username);
        if (num > 0) {
            return new JsonResult(StatusCode.USERNAME_EXISTS);
        }
        User user = new User();
        BeanUtils.copyProperties(userRegParam, user);
        user.setCreateTime((new Date()));
        userMapper.insertUser(user);
        return JsonResult.ok();
    }
    @PostMapping("login")
    @ApiOperation("用户登录")
    @ApiOperationSupport(order=20)
    public JsonResult login(@RequestBody UserLoginParam userLoginParam, @ApiIgnore HttpSession session){
        log.debug("userLoginParam="+userLoginParam);
        UserVO userVO = userMapper.selectByUsernameAndPassword(userLoginParam);
        if(userVO == null){
            return new JsonResult(StatusCode.USERNAME_PASSWORD_ERROR);
        }
        session.setAttribute("user",userVO);
        return JsonResult.ok(userVO);
    }

}
